//
//  HomeViewController.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/15.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit


class HomeViewController: XJVisitorController {
    
    let homeStatusID = "homeStatusID"
    
    lazy var homeStatusViewModel: XJHomeStatusViewModel = XJHomeStatusViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //没有登录的情况下设置访客视图
        if userLogon == false {
            
            visitorView.setVisitorInfo(nil, message: nil)
            return
        }
        tableView.registerClass(XJHomeStatusCell.self, forCellReuseIdentifier: homeStatusID)
        
        loadHomeData()
        setupUI()
        
        
    }
    
    private func setupUI(){
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 250
        tableView.separatorStyle = .None
        tableView.backgroundColor = UIColor.grayColor()
        
        tableView.tableFooterView = pullupView
        self.tableView.addSubview(RefreshVC)
        RefreshVC.addTarget(self, action: "loadHomeData", forControlEvents: UIControlEvents.ValueChanged)
       
    self.navigationController!.view.insertSubview(pullDownTips, belowSubview: self.navigationController!.navigationBar)
//        self.navigationController?.view.addSubview(pullDownTips)
    }
    
    /**
     显示下拉刷新提示label
     */
    private func showPullDownTips(count: Int){
    
        //判断是否在显示,在显示则不用重复刷新
        if pullDownTips.hidden == false{
            return
        }
        //设置初始位置
        pullDownTips.frame.origin.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - pullDownTips.frame.height
        
        pullDownTips.hidden = false
        
        //生成显示的文字内容
        let text = count > 0 ? "\(count)条新微博":"没有微博数据"
        pullDownTips.text = text
        
        //执行显示的动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.pullDownTips.transform = CGAffineTransformMakeTranslation(0, self.pullDownTips.frame.height)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.pullDownTips.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        
                        self.pullDownTips.hidden = true
                })
        }
        
    }
    
    /**
     获取数据(微博接口数据)
     */
    
    func loadHomeData(){
        
        homeStatusViewModel.loadData(pullupView.isAnimating(), finished: { (isSuccess, count) -> () in
            
            if isSuccess {
                
                self.tableView.reloadData()
            }else{
                
                print("请求数据失败")
            }
            
            //是下拉刷新就显示提示label
            if self.pullupView.isAnimating() == false {
                self.showPullDownTips(count)
            }
        })
        endRefresh()
        
    }
    
         /// 停止菊花转
    private func endRefresh(){
        pullupView.stopAnimating()
        RefreshVC.endRefreshing()
        
    }
    
    // MARK: - 懒加载控件
    /// 下拉刷新的提示label
    private lazy var pullDownTips: UILabel = {
    
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 14)
        label.hidden = true
        label.textAlignment = .Center
        label.backgroundColor = UIColor.orangeColor()
        label.frame.size = CGSize(width: SCREENW, height: 35)
        
        return label
    }()
    /// 懒加载上拉控件tableView.footerView
    private lazy var pullupView: UIActivityIndicatorView = {
    
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicatorView.color = UIColor.whiteColor()
        
//        indicatorView.hidesWhenStopped = false
        return indicatorView
    }()
    
    /// 懒加载顶部刷新控件
    private lazy var RefreshVC: XJRefreshControl = XJRefreshControl()
   
}

// MARK: - tableView
extension HomeViewController {
    
    /**
     加载某个cell时调用
     */
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        //判断是否要加载最后一个cell
        if indexPath.row == homeStatusViewModel.statusArr!.count - 1 && !pullupView.isAnimating(){
        
            //菊花转,加载数据
            pullupView.startAnimating()
            loadHomeData()
        }
    }

    /**
    tableView数据源方法
    */
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return homeStatusViewModel.statusArr?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView .dequeueReusableCellWithIdentifier(homeStatusID, forIndexPath: indexPath) as! XJHomeStatusCell

        cell.statusViewModel = homeStatusViewModel.statusArr![indexPath.row]
        return cell
    }
   
}